export function getDay(date) {
  var date2 = new Date();
  var date1 = new Date(date);
  var iDays = parseInt(
    Math.abs(date2.getTime() - date1.getTime()) / 1000 / 60 / 60 / 24
  );
  return iDays;
}

export function formatDate(date) {
  var tempDate = new Date(date);
  var year = tempDate.getFullYear();
  var month = tempDate.getMonth() + 1;
  var day = tempDate.getDate();
  var hour = tempDate.getHours();
  var min = tempDate.getMinutes();
  var second = tempDate.getSeconds();
  var week = tempDate.getDay();
  var str = '';
  if (week === 0) {
    str = '星期日';
  } else if (week === 1) {
    str = '星期一';
  } else if (week === 2) {
    str = '星期二';
  } else if (week === 3) {
    str = '星期三';
  } else if (week === 4) {
    str = '星期四';
  } else if (week === 5) {
    str = '星期五';
  } else if (week === 6) {
    str = '星期六';
  }
  if (hour < 10) {
    hour = '0' + hour;
  }
  if (min < 10) {
    min = '0' + min;
  }
  if (second < 10) {
    second = '0' + second;
  }
  return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ' ' + str;
}


/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 当前日期
export function getNowDate() {
  var myDate = new Date;
  var year = myDate.getFullYear(); //获取当前年
  var mon = myDate.getMonth() + 1; //获取当前月
  var date = myDate.getDate(); //获取当前日
  var now = year + "-" + mon + "-" + date;
  return now;
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return `星期${ ['日', '一', '二', '三', '四', '五', '六'][value]}` }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params;
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = dateRange[0];
    search.params['endTime'] = dateRange[1];
  } else {
    search.params['begin' + propName] = dateRange[0];
    search.params['end' + propName] = dateRange[1];
  }
  return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return "";
  }
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value == ('' + value)) {
      actions.push(datas[key].label);
      return true;
    }
  })
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  if (value === undefined || value.length ===0) {
    return "";
  }
  if (Array.isArray(value)) {
    value = value.join(",");
  }
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    var match = false;
    Object.keys(datas).some((key) => {
      if (datas[key].value == ('' + temp[val])) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
      }
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator);
    }
  })
  return actions.join('').substring(0, actions.join('').length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments, flag = true, i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  }
  return source;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

/**
* 参数处理
* @param {*} params  参数
*/
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}


// 返回项目路径
export function getNormalPath(p) {
  if (p.length === 0 || !p || p == 'undefined') {
    return p
  };
  let res = p.replace('//', '/')
  if (res[res.length - 1] === '/') {
    return res.slice(0, res.length - 1)
  }
  return res;
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
/** 公式相关计算函数 */
// 加法
export function accAdd (arg1, arg2) {
  let count1 = 0
  let count2 = 0
  if (arg1 === null || arg1 == "" || arg1 === undefined) {
    count1 = 0
  } else {
    count1 = arg1
  }
  if (arg2 === null || arg2 == "" || arg2 === undefined) {
    count2 = 0
  } else {
    count2 = arg2
  }
  var r1,r2,m;
  try{r1=count1.toString().split(".")[1].length}catch(e){r1=0}
  try{r2=count2.toString().split(".")[1].length}catch(e){r2=0}
  m=Math.pow(10,Math.max(r1,r2));
  return (floatMul(count1,m)+floatMul(count2,m))/m;
}
// 减法
export function floatSet(arg1,arg2){    
  var r1,r2,m,n;    
  try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}    
  try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}    
  m=Math.pow(10,Math.max(r1,r2));    
  //动态控制精度长度    
  n=(r1>=r2)?r1:r2;    
  return ((arg1*m-arg2*m)/m).toFixed(n);    
}
// 乘法
export function floatMul(arg1,arg2) {
  if (arg1 === null || arg1 === undefined || arg1 === "" || arg1 === "0" || arg1 === 0 || arg2 === null || arg2 === undefined || arg2 === "" || arg2 === "0" || arg2 === 0) {
    return 0
  } else {
    var m=0,s1=arg1.toString(),s2=arg2.toString(); 
    try{m+=s1.split(".")[1].length}catch(e){} 
    try{m+=s2.split(".")[1].length}catch(e){} 
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m); 
  }
}
// 除法
export function floatDiv(arg1,arg2){
  let newarg1 = Number(arg1)
  let newarg2 = Number(arg2) 
  if (arg1 === null || arg1 === undefined || arg1 === "" || arg1 === "0" || arg1 === 0 || arg2 === null || arg2 === undefined || arg2 === "" || arg2 === "0" || arg2 === 0) {
    return 0
  } else {
    var t1=0,t2=0,r1,r2; 
    try{t1=newarg1.toString().split(".")[1].length}catch(e){} 
    try{t2=newarg2.toString().split(".")[1].length}catch(e){} 
      
    r1=Number(newarg1.toString().replace(".","")); 
    
    r2=Number(newarg2.toString().replace(".","")); 
    return (r1/r2)*Math.pow(10,t2-t1); 
  }
}
// 保留小数
export function floatSub (num, decimal) {
  num = num.toString()
  let index = num.indexOf('.')
  if (index !== -1) {
      num = num.substring(0, decimal + index + 1)
  } else {
      num = num.substring(0)
  }
  return parseFloat(Number(num).toFixed(decimal))
  
}
// 四舍五入保留小数
export function fomatFloat(num, n){
  var f = parseFloat(num);
  if(isNaN(f)){
      return 0;
  }   
  f = Math.round(num*Math.pow(10, n))/Math.pow(10, n); // n 幂   
  var s = f.toString();
  var rs = s.indexOf('.');
  //判定如果是整数，增加小数点再补0
  if(rs < 0){
      rs = s.length;
      s += '.'; 
  }
  while(s.length <= rs + n){
      s += '0';
  }
  return s;
}
// 四舍五入
// 取最大
// 取最小
// 向上取整
// Math.ceil()
export function ceillCount (num) {
  let count = 0
  if (num === null || num === undefined || num === "" || num === "0" || num === 0 ) {
    count =  0
  } else {
    count = Math.ceil(Number(num))
  }
  return count
}
// 向下取整
export function initNumberChinese(value){  
  let chineseUnit = {  
    1000: "千",  
    10000: "万",  
    100000000: "亿",  
    1000000000000: "兆",  
    10000000000000000:'京',
    100000000000000000000:'垓'
  };  
  for (let unit of  Object.keys(chineseUnit).reverse()) {  
    let number = parseInt(unit);  
    if (value >= number) {  
      let quotient = Math.floor(value / number);  
      let remainder = value % number;  
  
      if (remainder > 0) {  
        return quotient + chineseUnit[number] + initNumberChinese(remainder);  
      } else {  
        return quotient + chineseUnit[number];  
      }  
    }  
  }  
  return value;  
}


// 数组里随机选取个数
export function getRandomImages(imagesCopy, count) {  
  // 创建一个副本，避免影响原始数组  
  const randomImages = [];  
  count = imagesCopy.length>count ? count : imagesCopy.length
  while (randomImages.length < count) {  
      // 生成一个随机索引  
      const randomIndex = Math.floor(Math.random() * imagesCopy.length);  
      // 将随机选中的图片添加到结果数组中  
      randomImages.push(imagesCopy[randomIndex]);  
      // 从副本数组中移除已选中的图片，以避免重复选择  
      imagesCopy.splice(randomIndex, 1);  
  }  

  return randomImages;  
}

export const  getRandomInt=(min, max)=> {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
